package pub.tbc.delay;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import pub.tbc.delay.domain.DelayTaskDefine;
import pub.tbc.toolkit.Objs;
import redis.clients.jedis.Jedis;

import java.util.concurrent.TimeUnit;

/**
 * @author tbc on 2017/8/9 10:03:49.
 */
@Slf4j
public class DefaultDelayExecutor implements DelayExecutor {

    private Jedis jedis = null;

    private void check(DelayTaskDefine taskDefine) {
        if (Objs.isEmpty(taskDefine)) {
            throw new RuntimeException("任务不能为空");
        }
        if (Objs.isEmpty(taskDefine.getBean())) {
            throw new RuntimeException("要执行的bean名称不能为空");
        }
        if (Objs.isEmpty(taskDefine.getMethod())) {
            throw new RuntimeException("要执行的方法名称不能为空");
        }
        if (Objs.isEmpty(taskDefine.getDelay())) {
            throw new RuntimeException("执行延时时间不能为空");
        }
        if (Objs.isEmpty(taskDefine.getTimeUnit())) {
            taskDefine.setTimeUnit(TimeUnit.SECONDS);
        }
    }

    /**
     * key值，为保证集群环境下的唯一性
     */
    private String getKey(DelayTaskDefine taskDefine) {
        return taskDefine.getBean() + "." + taskDefine.getMethod();
    }

    /**
     * 任务执行
     */
    public void exec(DelayTaskDefine taskDefine) {

    }

    @Override
    public void execute(final DelayTaskDefine taskDefine) {
        // 检查任务合法性
        check(taskDefine);

        // 任务持久化
        // redis.save(taskDefine);
        jedis.append(getKey(taskDefine), JSON.toJSONString(taskDefine));

        // 启动定时任务
        ThreadPool.getScheduledExecutor().schedule(new Runnable() {
            @Override
            public void run() {
                exec(taskDefine);
                // 清除持久化任务
                // todo
                jedis.del(getKey(taskDefine));
            }
        }, taskDefine.getDelay(), taskDefine.getTimeUnit());
    }
}
